from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
import pymysql
from typing import Optional

# Define the APIRouter
user = APIRouter()


# Database connection
def get_db_connection():
    """
    Create and return a MySQL database connection.
    """
    return pymysql.connect(
        host="localhost",
        user="root",  # Replace with your MySQL username
        password="17884873770",  # Replace with your MySQL password
        database="spider01",  # Database name
        charset="utf8mb4"
    )


# Request model for login
class LoginRequest(BaseModel):
    username: str
    password: str


@user.post("/login")
async def login(login_request: LoginRequest):
    """
    Handle user login.
    """
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            # Query the user by username
            sql = "SELECT id, password FROM users WHERE username = %s"
            cursor.execute(sql, (login_request.username,))
            result = cursor.fetchone()

            if result is None:
                raise HTTPException(status_code=404, detail="User not found")

            user_id, stored_password = result

            # Validate password (assuming plain text for simplicity; use hashing in production!)
            if login_request.password != stored_password:
                raise HTTPException(status_code=401, detail="Invalid password")

            return {"code": 200, "message": "登录成功", "data": user_id}


    finally:
        connection.close()
